import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';

import '../utils/http_helper.dart';
import '../utils/user_manager.dart';
import '../widgets/login_dialog.dart';
import '../widgets/webview_page.dart';
import 'mine/model/gems_model.dart';

class PremiumScreen extends StatefulWidget {
  const PremiumScreen({super.key});

  @override
  State<PremiumScreen> createState() => _PremiumScreenState();
}

class _PremiumScreenState extends State<PremiumScreen> {
  int _currentPage = 0;

  // IAP 实例
  final FlutterInappPurchase _iap = FlutterInappPurchase.instance;

  // 订阅产品ID
  final List<String> subscriptionIds = [];

  final List<String> originIds = [
    'comic.kkyotoon.yue1',
    'comic.kkyotoon.yue6',
    'comic.kkyotoon.yue12'
  ];

  // 状态变量
  List<Purchase> _activeSubscriptions = [];
  Purchase? _currentSubscription;
  bool _hasActiveSubscription = false;
  bool _isProcessing = false;
  bool _connected = false;
  bool _isConnecting = true;
  bool _isLoadingProducts = false;

  // 流订阅
  StreamSubscription<Purchase>? _purchaseUpdatedSubscription;
  StreamSubscription<PurchaseError>? _purchaseErrorSubscription;

  // 跟踪已处理的交易
  final Set<String> _processedTransactionIds = {};

  List<GemsModel> _subscripPackages = [];

  @override
  void initState() {
    super.initState();
    _initConnection();
    _setupListeners();
  }

  bool _isSubscribed() {
    if (_activeSubscriptions.isEmpty) {
      return false;
    } else {
      return _activeSubscriptions.any(
        (p) => p.productId == _subscripPackages[_currentPage].code,
      );
    }
  }

  @override
  void dispose() {
    _purchaseUpdatedSubscription?.cancel();
    _purchaseErrorSubscription?.cancel();
    _iap.endConnection();
    super.dispose();
  }

  void _setupListeners() {
    // 监听购买更新
    _purchaseUpdatedSubscription = _iap.purchaseUpdatedListener.listen(
      (purchase) async {
        debugPrint('🎯 Purchase updated: ${purchase.productId}');
        debugPrint('  Platform: ${purchase.platform}');
        debugPrint('  Purchase state: ${purchase.purchaseState}');

        final transactionId = purchase.transactionIdFor;
        final iosTransactionState = purchase.iosTransactionState;

        if (!mounted) {
          debugPrint('  ⚠️ Widget not mounted, ignoring update');
          return;
        }

        // 检查重复处理
        final transactionKey = transactionId ?? purchase.purchaseToken ?? '';
        if (transactionKey.isNotEmpty &&
            _processedTransactionIds.contains(transactionKey)) {
          debugPrint('  ⚠️ Transaction already processed: $transactionKey');
          return;
        }

        // 处理购买 - 检查多个条件
        bool isPurchased = false;

        // 对于iOS - 简单的逻辑
        final bool condition1 =
            iosTransactionState == TransactionState.purchased;
        bool condition2 = purchase.purchaseToken != null &&
            purchase.purchaseToken!.isNotEmpty;
        final bool condition3 = transactionId != null;

        // 对于iOS，收到购买更新通常意味着成功
        isPurchased = condition1 || condition2 || condition3;
        debugPrint('  Final isPurchased: $isPurchased');

        if (isPurchased) {
          debugPrint('✅ Purchase detected as successful, updating UI...');

          // 标记为已处理
          if (transactionKey.isNotEmpty) {
            _processedTransactionIds.add(transactionKey);
          }

          // 立即更新UI
          if (mounted) {
            setState(() {
              // _purchaseResult = '✅ Purchase successful: ${purchase.productId}';
              _isProcessing = false;
            });
          }

          // 向服务器报告购买
          await _reportPurchaseToServer(purchase);

          // 确认/完成交易
          try {
            debugPrint('Calling finishTransaction...');
            await _iap.finishTransaction(purchase);
            debugPrint('Transaction finished successfully');
          } catch (e) {
            debugPrint('Error finishing transaction: $e');
          }

          // 刷新订阅
          await Future<void>.delayed(const Duration(milliseconds: 500));
          await _checkActiveSubscriptions();
        } else if (purchase.purchaseState == PurchaseState.Pending) {
          // 待处理
          if (!mounted) return;
          setState(() {
            // _purchaseResult = '⏳ Purchase pending: ${purchase.productId}';
          });
          EasyLoading.showToast('⏳ Purchase pending: ${purchase.productId}');
        } else {
          // 未知状态
          if (!mounted) return;
          setState(() {
            _isProcessing = false;
            // _purchaseResult = '⚠️ Purchase received but state unknown';
          });
          EasyLoading.showToast('⚠️ Purchase received but state unknown');
        }
      },
      onError: (Object error) {
        debugPrint('Purchase stream error: $error');
        if (!mounted) return;
        setState(() {
          _isProcessing = false;
          // _purchaseResult = '❌ Stream error: $error';
        });
        EasyLoading.showToast('❌ Stream error: $error');
      },
    );

    // 监听购买错误
    _purchaseErrorSubscription = _iap.purchaseErrorListener.listen(
      (error) {
        debugPrint('Purchase error: ${error.code} - ${error.message}');

        if (!mounted) return;

        setState(() {
          _isProcessing = false;
          if (error.code == ErrorCode.UserCancelled) {
            // _purchaseResult = '⚠️ Purchase cancelled';
            EasyLoading.showToast('⚠️ Purchase cancelled');
          } else {
            // _purchaseResult = '❌ Error: ${error.message}';
            EasyLoading.showToast('❌ Error: ${error.message}');
          }
        });
      },
      onError: (Object error) {
        debugPrint('Error stream error: $error');
      },
    );
  }

  Future<void> _reportPurchaseToServer(Purchase purchase) async {
    if (originIds.contains(purchase.productId) == false) {
      return;
    }

    try {
      debugPrint('🌐 Reporting purchase to server: ${purchase.productId}');
      EasyLoading.show();
      // 构建上报数据
      final purchaseData = {
        'validId': purchase.productId,
        'appleReceipt': purchase.purchaseToken,
        'transactionId': purchase.transactionIdFor,
        'isSanDbox': false,
        'type': 0,
      };

      // 使用HttpUtil发送到服务器
      final response = await HttpUtil().postModel(
        'ComicMember/ValidApple', // 替换为实际的API端点
        data: purchaseData,
        fromJson: (json) => json,
      );
      if (response?.status == 200) {
        EasyLoading.showToast('✅ Subscription successful');
        await _checkActiveSubscriptions();

        // 延迟执行导航，确保所有状态更新完成
        if (mounted) {
          await Future.delayed(const Duration(milliseconds: 100));
          if (mounted && Navigator.of(context).canPop()) {
            Navigator.of(context).pop(true);
          }
        }
      } else {
        EasyLoading.showError(response?.message ?? "Subscription fail");
      }
      EasyLoading.dismiss();
      print("上报结果: $response");
    } catch (e) {
      debugPrint('❌ Error reporting purchase to server: $e');
      EasyLoading.dismiss();
    }
  }

  Future<void> _initConnection() async {
    try {
      final result = await _iap.initConnection();
      debugPrint('Connection initialized: $result');

      if (!mounted) return;

      setState(() {
        _connected = result;
        _isConnecting = false;
      });

      if (_connected) {
        await _loadSubscriptions();
        await _checkActiveSubscriptions();
      }
    } catch (error) {
      debugPrint('Failed to initialize connection: $error');
      if (!mounted) return;
      setState(() {
        _connected = false;
        _isConnecting = false;
      });
    }
  }

  Future<void> _loadSubscriptions() async {
    setState(() {
      _isLoadingProducts = true;
    });
    try {
      final response = await HttpUtil().getModel<List<GemsModel>>(
        'ComicMember/GetVipPriceLists',
        fromJson: (json) =>
            (json as List).map((item) => GemsModel.fromJson(item)).toList(),
      );
      if (response?.status == 200 && response?.result != null) {
        if (!mounted) return;
        setState(() {
          _isLoadingProducts = false;
          _subscripPackages = response?.result ?? [];
        });
      } else {
        if (!mounted) return;
        setState(() {
          _isLoadingProducts = false;
          _subscripPackages = [];
        });
      }
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isLoadingProducts = false;
        _subscripPackages = [];
      });
    }
  }

  Future<void> _checkActiveSubscriptions() async {
    if (!_connected) return;

    try {
      // 获取所有可用的购买
      final purchases = await _iap.getAvailablePurchases();

      debugPrint('=== Checking Active Subscriptions ===');
      debugPrint('Total purchases found: ${purchases.length}');

      // 从订阅包中获取产品ID列表
      final validProductIds = _subscripPackages
          .map((pkg) => pkg.code)
          .where((code) => code != null)
          .cast<String>()
          .toList();
      debugPrint('Valid product IDs from packages: $validProductIds');

      // 打印所有购买记录的产品ID
      for (final purchase in purchases) {
        debugPrint(
            'Found purchase - Product ID: ${purchase.productId}, State: ${purchase.purchaseState}');
      }

      // 过滤订阅 - 使用从服务器获取的产品ID
      final activeSubs = purchases
          .where((p) => validProductIds.contains(p.productId))
          .toList();

      debugPrint("activeSubsactiveSubs = $activeSubs");
      debugPrint("Active subscriptions count: ${activeSubs.length}");

      if (!mounted) return;

      setState(() {
        _activeSubscriptions = activeSubs;
        _hasActiveSubscription = activeSubs.isNotEmpty;
        _currentSubscription = activeSubs.isNotEmpty ? activeSubs.first : null;
      });
    } catch (error) {
      debugPrint('Failed to check active subscriptions: $error');
    }
  }

  Future<void> _purchaseSubscription(String productId) async {
    final isLoggedIn = await UserManager.isLoggedIn();
    if (isLoggedIn) {
      if (_isProcessing) {
        debugPrint('⚠️ Already processing a purchase, ignoring');
        return;
      }

      // 直接使用productId，不再从_subscriptions中查找
      debugPrint('🛒 Starting subscription purchase: $productId');

      setState(() {
        _isProcessing = true;
      });

      try {
        // iOS
        final requestProps = RequestPurchaseProps.subs(
          request: RequestSubscriptionPropsByPlatforms(
            ios: RequestSubscriptionIosProps(sku: productId),
          ),
        );

        await _iap.requestPurchase(requestProps);
        debugPrint('Purchase request sent, waiting for response...');
      } catch (error) {
        debugPrint('Failed to request subscription: $error');
        if (!mounted) return;
        setState(() {
          _isProcessing = false;
          // _purchaseResult = '❌ Failed to request: $error';
        });
        EasyLoading.showToast('❌ Failed to request: $error');
      }
    } else {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const LoginDialog(),
      );
    }
  }

  Future<void> _restorePurchases() async {
    setState(() {
      _isProcessing = true;
    });

    try {
      final purchases = await _iap.getAvailablePurchases();
      debugPrint('Restored ${purchases.length} purchases');

      if (!mounted) return;

      setState(() {
        _activeSubscriptions = purchases
            .where((p) => subscriptionIds.contains(p.productId))
            .toList();
        _hasActiveSubscription = _activeSubscriptions.isNotEmpty;
        _currentSubscription =
            _activeSubscriptions.isNotEmpty ? _activeSubscriptions.first : null;
        _isProcessing = false;
        // _purchaseResult =
        // '✅ Restored ${_activeSubscriptions.length} subscriptions';
        EasyLoading.showToast(
          '✅ Restored ${_activeSubscriptions.length} subscriptions',
        );
      });
    } catch (error) {
      debugPrint('Failed to restore purchases: $error');
      if (!mounted) return;
      setState(() {
        _isProcessing = false;
      });
      EasyLoading.showToast('❌ Failed to restore: $error');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF211839),
      appBar: AppBar(
        backgroundColor: const Color(0xFF211839),
        elevation: 0,
        centerTitle: true,
        title: const Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.diamond, color: Colors.amber, size: 24),
            SizedBox(width: 8),
            Text(
              'Premium',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontStyle: FontStyle.italic,
                fontSize: 20,
              ),
            ),
          ],
        ),
        actions: [
          // 恢复购买按钮
          TextButton(
            onPressed: _restorePurchases,
            child: const Text("Restore", style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
      body: SafeArea(
        child: _isConnecting
            ? const Center(child: CircularProgressIndicator())
            : SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    children: [
                      // 功能说明卡片
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(20),
                        decoration: BoxDecoration(
                          color: const Color(0xFF3D2F5A).withValues(alpha: 0.6),
                          borderRadius: BorderRadius.circular(16),
                          border: Border.all(
                            color: const Color(0xFF9C88FF).withOpacity(0.3),
                            width: 1,
                          ),
                        ),
                        child: const Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Premium Benefits',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            SizedBox(height: 8),
                            Text(
                              '• Monthly gift pack\n'
                              '• Exclusive logo\n'
                              '• Remove Ads\n'
                              '• Unlock premium comics\n'
                              '• Read in advance',
                              style: TextStyle(
                                color: Color(0xFFB8B3C7),
                                fontSize: 13,
                                height: 1.5,
                              ),
                            ),
                          ],
                        ),
                      ),

                      const SizedBox(height: 20),

                      // 订阅选项
                      _isLoadingProducts
                          ? const Center(child: CircularProgressIndicator())
                          : SizedBox(
                              height: 180,
                              child: PageView.builder(
                                onPageChanged: (index) {
                                  setState(() {
                                    _currentPage = index;
                                  });
                                },
                                itemCount: _subscripPackages.length,
                                itemBuilder: (context, index) {
                                  GemsModel pkg = _subscripPackages[index];

                                  final isActive = _hasActiveSubscription &&
                                      _currentSubscription?.productId ==
                                          pkg.code;

                                  return _buildSubscriptionCard(
                                    title: pkg.name ?? '',
                                    description: pkg.desc ?? '',
                                    price: pkg.amount?.toString() ?? '',
                                    isActive: isActive,
                                  );
                                },
                              ),
                            ),

                      const SizedBox(height: 12),
                      // 指示器
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: List.generate(
                          _subscripPackages.length,
                          (index) => Container(
                            margin: const EdgeInsets.symmetric(horizontal: 4),
                            width: _currentPage == index ? 12 : 8,
                            height: 8,
                            decoration: BoxDecoration(
                              color: _currentPage == index
                                  ? Colors.purple
                                  : Colors.grey.shade600,
                              borderRadius: BorderRadius.circular(4),
                            ),
                          ),
                        ),
                      ),

                      const SizedBox(height: 24),

                      // 订阅按钮
                      SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          onPressed: _isProcessing
                              ? null
                              : _isSubscribed()
                                  ? () {} // 已订阅时提供空函数而不是null，这样按钮会显示但不执行任何操作
                                  : () => _purchaseSubscription(
                                        _subscripPackages[_currentPage].code ??
                                            '',
                                      ),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: _isSubscribed()
                                ? Colors.amber.withValues(alpha: 0.7)
                                : Colors.amber,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(vertical: 14),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25),
                            ),
                          ),
                          child: _isProcessing
                              ? const CircularProgressIndicator()
                              : Text(
                                  _isSubscribed()
                                      ? "Subscribed"
                                      : _subscripPackages.isEmpty
                                          ? "Subscribe"
                                          : _subscripPackages[_currentPage]
                                                  .name ??
                                              '',
                                  style: const TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                        ),
                      ),

                      const SizedBox(height: 20),

                      Text.rich(
                        TextSpan(
                          text: "By subscribing, you agree to our ",
                          style: const TextStyle(
                              color: Colors.white70, fontSize: 12),
                          children: [
                            TextSpan(
                              text: "EULA",
                              style: const TextStyle(
                                  color: Colors.blueAccent,
                                  decoration: TextDecoration.underline),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  // _launchUrl("https://www.example.com/eula");
                                  //
                                  _navigateToWebView(
                                    "EULA",
                                    "https://www.apple.com/legal/internet-services/itunes/dev/stdeula/",
                                  );
                                },
                            ),
                            const TextSpan(text: ", "),
                            TextSpan(
                              text: "Subscription Terms",
                              style: const TextStyle(
                                  color: Colors.blueAccent,
                                  decoration: TextDecoration.underline),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  // _launchUrl(
                                  //     "https://www.example.com/subscription-terms");
                                  //
                                  _navigateToWebView(
                                    "Subscription Terms",
                                    "https://sites.google.com/view/funtoonsubscription/",
                                  );
                                },
                            ),
                            const TextSpan(text: " and "),
                            TextSpan(
                              text: "Privacy Policy",
                              style: const TextStyle(
                                  color: Colors.blueAccent,
                                  decoration: TextDecoration.underline),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  // _launchUrl("https://www.example.com/privacy");
                                  _navigateToWebView(
                                    "Privacy Policy",
                                    "https://www.privacypolicies.com/live/01b48fbe-048a-4c57-b276-41d5c1e8e789",
                                  );
                                },
                            ),
                          ],
                        ),
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 20),

                      // 订阅说明
                      const Text(
                        'Your subscription will automatically renew unless canceled at least 24 hours before the end of the current period. '
                        'Payment will be charged to your Apple ID account at confirmation of purchase. '
                        'You can manage and cancel your subscriptions by going to your account settings in the App Store.',
                        style: TextStyle(
                          color: Color(0xFF8A7CA8),
                          fontSize: 12,
                          height: 1.5,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ],
                  ),
                ),
              ),
      ),
    );
  }

  // Navigate to WebView page
  void _navigateToWebView(String title, String url) {
    if (mounted) {
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => WebViewPage(title: title, url: url),
        ),
      );
    }
  }

  Widget _buildSubscriptionCard({
    required String title,
    required String description,
    required String price,
    bool isActive = false,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: isActive ? Colors.green.shade400 : Colors.purple.shade400,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: const Color(0xFF9C88FF).withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  title,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              if (isActive) ...[
                const SizedBox(width: 8),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 2,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white24,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: const Text(
                    "Current Plan",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ],
          ),
          const SizedBox(height: 8),
          Text(
            description,
            style: const TextStyle(
              color: Colors.white70,
              fontSize: 12,
              height: 1.3,
            ),
          ),
          const Spacer(),
          Text(
            "\$$price",
            style: const TextStyle(
              color: Colors.white,
              fontSize: 22,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }
}
